<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * 计算分销商佣金类
 * Class Model_Fenxiao_Commission
 */
class Model_Fenxiao_Commission
{
    public static function pay_commission($order)
    {
        //获取当前订单的分销商分佣设置信息(之前已经算好的)
        $fenxiao_data = DB::select()->from('fenxiao_data')->where('order_id', '=', $order['id'])->execute()->current();
        //如果fenxiao_data表没有此订单的分佣比例数据,则直接返回
        if (empty($fenxiao_data)) {
            return false;
        }

        $level_names = array(1 => '一级', 2 => '二级', 3 => '三级');
        //购买分销商
        $cur_fenxiao_model = ORM::factory('fenxiao')->where('memberid', '=', $order['memberid'])->find();
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        if (!$cur_fenxiao_model->loaded()) {
            return;
        }
        $fenxiaoArr = array();
        //1级分销商
        $fenxiaoArr[] = Model_Fenxiao::get_ancestor_fenxiao_info($order['memberid'], 1);
        //二级分销商
        $fenxiaoArr[] = Model_Fenxiao::get_ancestor_fenxiao_info($order['memberid'], 2);
        if ($level_num == 0 || $level_num == 3) {
            //3级分销商
            $fenxiaoArr[] = Model_Fenxiao::get_ancestor_fenxiao_info($order['memberid'], 3);
        }
        $curtime = time();
        $compute_info = Model_Member_Order_Compute::get_income_info($order['id']);
        $member_order_compute = DB::select()->from('member_order_compute')->where("order_id={$order['id']}")->execute()->current();

        try {
            //分销返佣(依次三级->二级->一级)
            foreach ($fenxiaoArr as $k => $v) {
                if ($v) {
                    $number = $k + 1;
                    //判断是否计算过佣金.
                    $hasNum = ORM::factory('fenxiao_record')
                        ->where('memberid', '=', $v['memberid'])
                        ->and_where('fxmemberid', '=', $order['memberid'])
                        ->and_where('type', '=', 0)
                        ->and_where('orderid', '=', $order['id'])
                        ->count_all();
                    if ($hasNum > 0) {
                        continue;
                    }
                    $fenxiaoModel = ORM::factory('fenxiao', $v['id']);
                    if ($fenxiaoModel->loaded()) {
                        if ($fenxiaoModel->isfrozen == 1) {
                            continue;
                        }
                        //使用下单时已算好的佣金
                        $payAmount = $member_order_compute['fx_top'.$number];

                        $fxrankid = Model_Fenxiao::get_rankid($v['memberid']);
                        $fenxiaoModel->fxrankid = $fxrankid;
                        $fenxiaoModel->save();

                        $member_out = DB::select()->from('member')->where('mid', '=', $order['memberid'])->execute()->current();
                        $member_out_nickname = $member_out['nickname'] . '[' . $order['memberid'] . ']';
                        $cur_level = Model_Fenxiao::get_rank($v['memberid'], $order['memberid']);
                        $description = $member_out_nickname . '订单<' . $order['ordersn'] . '>交易完成，' . $level_names[$cur_level] . '分销商获得返佣' . $payAmount . '元';

                        $deal_result = Model_Member::cash_deal($v['memberid'], $payAmount, 0, $description, false, $order['id']);

                        if ($deal_result['status']) {
                            $fenxiaoRecord = ORM::factory('fenxiao_record');
                            $fenxiaoRecord->memberid = $v['memberid'];
                            $fenxiaoRecord->type = 0;
                            $fenxiaoRecord->amount = $payAmount;
                            $fenxiaoRecord->orderid = $order['id'];
                            $fenxiaoRecord->fxmembertype = $k + 1;
                            $fenxiaoRecord->fxmemberid = $order['memberid'];
                            $fenxiaoRecord->addtime = $curtime;
                            $fenxiaoRecord->save();


                            if ($fxrankid) {
                                $rank_info = DB::select()->from('fenxiao_rank')
                                    ->where('id', '=', $fxrankid)
                                    ->execute()->current();
                                $jifen_label = DB::select('label')->from('jifen')
                                    ->where('id', '=', $rank_info['jifen_id'])
                                    ->execute()->get('label');
                                if (!empty($jifen_label)) {
                                    $jifen = Model_Jifen::reward_jifen($jifen_label, $v['memberid']);
                                    if (!empty($jifen)) {
                                        $jifen_desc = $rank_info['title'] . '分销商的分销订单完成获得' . $jifen . '积分';
                                        St_Product::add_jifen_log($v['memberid'], $jifen_desc, $jifen, 2);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //自购返佣
            if ($cur_fenxiao_model->status == 1 && $cur_fenxiao_model->isfrozen != 1) {
                $result = DB::select()->from('fenxiao_record')
                    ->where('type', '=', 0)
                    ->and_where('memberid', '=', $order['memberid'])
                    ->and_where('orderid', '=', $order['id'])
                    ->and_where('fxmemberid', '=', $order['memberid'])
                    ->execute()
                    ->current();
                if (!empty($result)) {
                    return;
                }
                //使用下单时就计算好的佣金
                $payAmount = $member_order_compute['fx_self'];

                $description = "分销商自购订单<" . $order['ordersn'] . ">交易完成，返佣" . $payAmount . '元';
                $deal_result = Model_Member::cash_deal($order['memberid'], $payAmount, 0, $description, false, $order['id']);

                if ($deal_result['status']) {
                    $fenxiaoRecord = ORM::factory('fenxiao_record');
                    $fenxiaoRecord->memberid = $order['memberid'];
                    $fenxiaoRecord->type = 0;
                    $fenxiaoRecord->amount = $payAmount;
                    $fenxiaoRecord->orderid = $order['id'];
                    $fenxiaoRecord->fxmembertype = 0;
                    $fenxiaoRecord->fxmemberid = $order['memberid'];
                    $fenxiaoRecord->addtime = $curtime;
                    $fenxiaoRecord->save();
                }
            }
            //$db->commit();
        } catch (Exception $ex) {

            self::write_log($ex->getMessage().$ex->getTraceAsString());
            //$db->rollback();

        }


    }

    /**
     * 计算佣金
     * @param $number
     * @param $fenxiao_data
     * @param $order
     * @param $platform_commission
     * @return float|int
     */
    public static function compute_commission($number, $fenxiao_data, $order, $platform_commission)
    {
        //订单实际价格
        $consumeAmount = floatval($order['total_price']);
        $payAmount = 0;
        //根据订单金额按比例
        if ($fenxiao_data['type' . $number] == 1) {
            $payAmount = floatval($consumeAmount * $fenxiao_data['fxratio' . $number]);
        } //按平台佣金分佣
        else {
            if ($fenxiao_data['type' . $number] == 2) {
                $payAmount = $platform_commission * $fenxiao_data['pm_fxratio' . $number];
            } else {
                //线路产品
                if ($order['typeid'] == 1) {
                    $payAmount = floatval($fenxiao_data['cash' . $number]) * intval($order['dingnum']) + floatval($fenxiao_data['cash' . $number . '_old']) * intval($order['oldnum']) + floatval($fenxiao_data['cash' . $number . '_child']) * intval($order['childnum']);
                    $payAmount += floatval($fenxiao_data['cash' . $number . '_people4']) * intval($order['people4_num']) + floatval($fenxiao_data['cash' . $number . '_people5']) * intval($order['people5_num']) + floatval($fenxiao_data['cash' . $number . '_people6']) * intval($order['people6_num']);
                } //游轮产品
                else {
                    if ($order['typeid'] == 104) {
                        $dingnum = DB::query(Database::SELECT, "select sum(dingnum) as num from sline_member_order_child where pid={$order['id']}")
                            ->execute()->get('num');
                        $payAmount = floatval($fenxiao_data['cash' . $number]) * intval($dingnum);
                    }
                    //户外产品,需要把小孩算进去.
                    else if($order['typeid'] == 114) {
                        $payAmount = floatval($fenxiao_data['cash' . $number]) * (intval($order['dingnum']) + intval($order['childnum']));
                    }
                    else {
                        $payAmount = floatval($fenxiao_data['cash' . $number]) * intval($order['dingnum']);
                    }
                }
            }
        }
        return $payAmount;
    }


    /**
     * 日志记录文件
     * @param $logs
     */
    public static function write_log($logs)
    {
        $payLogDir = BASEPATH . '/data/fenxiao_commission_logs/';
        if (!file_exists($payLogDir)) {
            mkdir($payLogDir, 0777, true);
        }
        if(is_array($logs)) $logs = print_r($logs,true);
        //日志文件
        $file = $payLogDir . date('ymd') . '.txt';
        $data = "=========================" . PHP_EOL;
        $data .= "Time:".date("Y-m-d H:i:s") . PHP_EOL;
        $data .= "result:{$logs}" . PHP_EOL;

        file_put_contents($file, $data, FILE_APPEND);
    }



}